<template>
  <div class="user-info" v-if="userStore.isAuthenticated">
    <el-dropdown @command="handleCommand" trigger="click">
      <div class="user-avatar">
        <el-avatar :icon="User" />
        <span class="username">{{ userStore.userInfo?.username }}</span>
      </div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="profile">个人中心</el-dropdown-item>
          <el-dropdown-item command="updatePassword">修改密码</el-dropdown-item>
          <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>

  <!-- 修改密码弹出框 -->
  <el-dialog v-model="passwordDialogVisible" title="修改密码" width="370px" :before-close="handleClose">
    <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="passwordForm.oldPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitPasswordChange">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { User } from '@element-plus/icons-vue'
import { useUser } from '@/store/user'
import { useTabs } from '@/store/tabs'
import md5 from 'js-md5'
import { apiChangePassword } from '@/api/system/user'

const router = useRouter()
const userStore = useUser()
const { closeAllTabs } = useTabs()

// 修改密码弹出框相关
const passwordDialogVisible = ref(false)
const passwordFormRef = ref<FormInstance>()
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule: any, value: any, callback: (error?: string | Error) => void) => {
  console.log(rule)
  if (value === '') {
    callback(new Error('请再次输入新密码'))
  } else if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = ref<FormRules>({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6到20个字符之间', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6到20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
})

const handleCommand = (command: any) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'updatePassword':
      // 打开修改密码弹出框
      passwordDialogVisible.value = true
      break
    case 'logout':
      ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userStore.logout()
        ElMessage.success('已退出登录')
        closeAllTabs()
        router.push('/login')
      })
      break
  }
}

// 关闭弹出框前的处理
const handleClose = () => {
  passwordDialogVisible.value = false
  // 重置表单
  passwordFormRef.value?.resetFields()
}

// 提交密码修改
const submitPasswordChange = async () => {
  if (!passwordFormRef.value) return
  try {
    await passwordFormRef.value.validate()
    // 调用修改密码接口
    const { code, message } = await apiChangePassword({
      oldPassword: md5.md5(passwordForm.value.oldPassword),
      newPassword: md5.md5(passwordForm.value.newPassword)
    })
    if (code !== 200) {
      ElMessage.error(message || '密码修改失败')
      return
    }
    ElMessage.success('密码修改成功')
    handleClose()
    userStore.logout()
    closeAllTabs()
    router.push('/login')
  } catch (error) {
    return
  }
}
</script>

<style scoped>
.user-info {
  display: flex;
  align-items: center;
  height: 100%;
}

.user-avatar {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin-left: 8px;
  font-size: 14px;
  color: var(--el-text-color-primary);
}
</style>